package com.summer.filter;

import com.summer.result.Result;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 允许所有域访问
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 允许的请求方法
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        // 允许的请求头
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
        // 预检请求（OPTIONS）的缓存时间（秒），减少重复预检
        response.setHeader("Access-Control-Max-Age", "3600");
        // 允许前端获取的响应头（如需暴露自定义头）
        response.setHeader("Access-Control-Expose-Headers", "Custom-Header");
        chain.doFilter(request, response);
//        HttpSession session = request.getSession(false);
//        String servletPath = request.getServletPath();
//        System.out.println("servletPath:" + servletPath);
//        if (servletPath.startsWith("/images/")) {
//            chain.doFilter(request, response);
//        } else if ("/user/login".equals(servletPath)
//                || "/user/exit".equals(servletPath)
//                || "/welcomeService".equals(servletPath)
//                || "/user/register".equals(servletPath)
//                || session != null && session.getAttribute("username") != null) {
//            chain.doFilter(request, response);
//        } else {
//            FailedLogin();
//        }
    }
//    private Result FailedLogin(){
//        return Result.error("请先登录");
//    }
}
